package com.yuanli.card.authentication.core.chain;


import com.yuanli.card.authentication.service.ISysResourcesService;
import com.yuanli.card.pojo.SysResources;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by layne on 2018/5/24.
 */
public class ShiroFilerChainManager {
    Logger logger = LoggerFactory.getLogger(ShiroFilerChainManager.class);

    @Autowired
    private ISysResourcesService resourcesService;

    @Autowired
    @Qualifier("shiroFilter")
    private ShiroFilterFactoryBean shiroFilterFactoryBean;

    public void updatePermission() {
        synchronized (shiroFilterFactoryBean) {
            logger.info("##################更新权限规则##################");
            AbstractShiroFilter shiroFilter = null;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
            } catch (Exception e) {
                logger.error("更新url资源权限获取shiroFilter 系统异常", e);
            }
            // 获取过滤管理器
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter
                    .getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();

            // 清空初始权限配置
            manager.getFilterChains().clear();

            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            try {
                loadShiroFilterChain().forEach((k, v) -> manager.createChain(k, v));
            } catch (Exception e) {
                logger.error("更新权限规则出错", e);
            }
        }
    }

    /**
     * @param shiroFilterFactoryBean
     */
    private Map<String, String> loadShiroFilterChain() {
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        List<SysResources> resources = resourcesService.findAll();
        // url : mroles[roleid]
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/**", "anon");
        return filterChainDefinitionMap;
    }
}
